/** 自定义指令 v-loading */
import Loading from "@/components/Loading/index.vue";
import { createApp } from "vue";

const CUSTOM_CLASS = "directive-loading-relative";
const CLASS_FLAG = "directive-loading";

/** 插入组件 */
const append = (el: HTMLElement) => {
	const node = createInstance();
	// 获取父节点样式，查看是否有定位属性
	const style = window.getComputedStyle(el, null);
	if (["absolute", "fixed", "relative"].indexOf(style.position) === -1) {
		el.classList.add(CUSTOM_CLASS);
	}
	el.appendChild(node);
};

const remove = (el: HTMLElement) => {
	el.classList.remove(CUSTOM_CLASS);
	el.removeChild(el.lastChild as Node);
};

/** 创建instance */
const createInstance = (): Node => {
	const app = createApp(Loading);
	const elNode = app.mount(document.createElement("div")).$el;
	// 添加类名标识
	elNode.classList.add(CLASS_FLAG);
	return elNode;
};

const vLoading = {
	mounted(el: HTMLElement, binding: any) {
		if (binding.value) {
			// 插入组件
			append(el);
		}
	},
	updated(el: HTMLElement, binding: any) {
		const lastChild = el.lastChild as HTMLElement;
		if (binding.value && (!lastChild || !lastChild.classList || !lastChild.classList.contains(CLASS_FLAG))) {
			// 插入组件
			append(el);
		} else if (!binding.value && lastChild && lastChild.classList?.contains(CLASS_FLAG)) {
			remove(el);
		}
	}
};

export default vLoading;
